package com.gt.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.Sides;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;

@Slf4j
public class PrintUtil {


    /**
     * 打印pdf
     * @param file
     * @return
     */
    public static int PrintPdf(File file) {
        // 读取pdf文件
        PDDocument document = null;
        int printResult = 8888;
        try {
//            File file = new File(filePath);
            int pageCount = 0;
            String printName = "Win32 Printer : 公司打印机";
            boolean isFindPrint = false;
            PrinterJob job = PrinterJob.getPrinterJob();
            // 遍历所有打印机的名称
            for (PrintService ps : PrinterJob.lookupPrintServices()) {
                String psName = ps.toString();
                // 使用指定打印机
                if (psName.equals(printName)) {
                    job.setPrintService(ps);
                    isFindPrint = true;
                    break;
                }
            }
            if (!isFindPrint) {
                log.error("打印机不在线");
                return 7777;
            }
            document = PDDocument.load(file);
            pageCount = document.getNumberOfPages();
//        job.setPageable(new PDFPageable(document));
            Paper paper = new Paper();
            // 设置打印纸张大小
            paper.setSize(598, 842); // 1/72 inch
            // 设置打印位置 坐标
            paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
            //初始化一个页面打印对象
            PageFormat pageFormat = new PageFormat();
            pageFormat.setPaper(paper);
            //设置页面打印方向，从上往下，从左往右
            pageFormat.setOrientation(PageFormat.PORTRAIT);

            // 设置打印属性
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            pras.add(new Copies(1)); // 设置打印份数
            pras.add(MediaSizeName.ISO_A4); // 设置纸张大小

            //要打印的文档
            Book book = new Book();
            // append all pages 设置一些属性 是否缩放 打印张数等
            // 缩放问题Scaling 实际大小ACTUAL_SIZE,缩小SHRINK_TO_FIT,拉伸STRETCH_TO_FIT,适应SCALE_TO_FIT;
            book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, pageCount);
            job.setPageable(book);
            // 开始打印
            job.print(pras);

        } catch (Exception e) {
            printResult = 7777;
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    log.error("打印关闭文档异常!");
                }
            }
        }
        return printResult;
    }

    /**
     * 打印pdf
     * @param filePath
     * @return
     */
    public static void PrintPdfByPath(String filePath) {
        // 读取pdf文件
        PDDocument document = null;
        try {
            File file = new File(filePath);
            int pageCount = 0;
            String printName = "Win32 Printer : 公司打印机";
            boolean isFindPrint = false;
            PrinterJob job = PrinterJob.getPrinterJob();
            // 遍历所有打印机的名称
            for (PrintService ps : PrinterJob.lookupPrintServices()) {
                String psName = ps.toString();
                // 使用指定打印机
                if (psName.equals(printName)) {
                    job.setPrintService(ps);
                    isFindPrint = true;
                    break;
                }
            }
            if (!isFindPrint) {
                log.error("打印机不在线");
            }
            document = PDDocument.load(file);
            pageCount = document.getNumberOfPages();
//        job.setPageable(new PDFPageable(document));
            Paper paper = new Paper();
            // 设置打印纸张大小
            paper.setSize(598, 842); // 1/72 inch
             //设置打印位置 坐标
            paper.setImageableArea(0, 0, paper.getWidth(),paper.getHeight()); // no margins
            //初始化一个页面打印对象
            PageFormat pageFormat = new PageFormat();
            pageFormat.setPaper(paper);
            //设置页面打印方向，从上往下，从左往右
            pageFormat.setOrientation(PageFormat.PORTRAIT);

            // 设置打印属性
//            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
//            pras.add(new Copies(1)); // 设置打印份数
//            pras.add(MediaSizeName.ISO_A4); // 设置纸张大小


            //要打印的文档
            Book book = new Book();
            // append all pages 设置一些属性 是否缩放 打印张数等
            // 缩放问题Scaling 实际大小ACTUAL_SIZE,缩小SHRINK_TO_FIT,拉伸STRETCH_TO_FIT,适应SCALE_TO_FIT;
            book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, pageCount);
            job.setPageable(book);
            // 开始打印
            job.print();

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    log.error("打印关闭文档异常!");
                }
            }
        }
    }


    /**
     * 打印图片
     * @param filePath
     */
    public static void PrintImage(String filePath) {
        FileInputStream imageStream = null;
        try {
            //需要打印的文件
            imageStream = new FileInputStream(new File(filePath));
            // 获取默认的打印服务
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            if (printService == null) {
                log.error("没有找到默认的打印服务！");
                return;
            }
            // 创建打印作业
            DocPrintJob printJob = printService.createPrintJob();
            // 设置打印属性
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            pras.add(new Copies(1)); // 设置打印份数
            pras.add(MediaSizeName.ISO_A4); // 设置纸张大小（这里以A4为例）
            pras.add(Sides.ONE_SIDED); // 设置单面打印
            // 创建打印文档
            DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
            SimpleDoc printDoc = new SimpleDoc(imageStream, flavor, null);
            // 执行打印作业
            printJob.print(printDoc, pras);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (imageStream != null) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    log.error("关闭流失败!");
                }
            }
        }

    }


    /**
     * 打印pdf
     * @param filePath
     * @return
     */
    public static void PrintPdfByPath1(String filePath) {
        // 读取pdf文件
        PDDocument document = null;
        try {
            File file = new File(filePath);
            int pageCount = 0;
            String printName = "Canon TS200 series";
            boolean isFindPrint = false;
            PrinterJob job = PrinterJob.getPrinterJob();
            // 遍历所有打印机的名称
            for (PrintService ps : PrinterJob.lookupPrintServices()) {
                String psName = ps.toString();
                // 使用指定打印机
                if (psName.equals(printName)) {
                    job.setPrintService(ps);
                    isFindPrint = true;
                    break;
                }
            }
            if (!isFindPrint) {
                log.error("打印机不在线");
            }
            document = PDDocument.load(file);
            pageCount = document.getNumberOfPages();
//        job.setPageable(new PDFPageable(document));
            Paper paper = new Paper();
            // 设置打印纸张大小
//            paper.setSize(598, 842); // 1/72 inch
            // 设置打印位置 坐标
//            paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
            //初始化一个页面打印对象
            PageFormat pageFormat = new PageFormat();
            pageFormat.setPaper(paper);
            //设置页面打印方向，从上往下，从左往右
            pageFormat.setOrientation(PageFormat.PORTRAIT);

            // 设置打印属性
//            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
//            pras.add(new Copies(1)); // 设置打印份数
//            pras.add(MediaSizeName.ISO_A4); // 设置纸张大小


            //要打印的文档
            Book book = new Book();
            // append all pages 设置一些属性 是否缩放 打印张数等
            // 缩放问题Scaling 实际大小ACTUAL_SIZE,缩小SHRINK_TO_FIT,拉伸STRETCH_TO_FIT,适应SCALE_TO_FIT;
            book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, pageCount);
            job.setPageable(book);
            // 开始打印
            job.print();

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    log.error("打印关闭文档异常!");
                }
            }
        }
    }

}


